<template>
	<a-modal
		:visible="visible"
		width="90vw"
		wrap-class-name="a-modal-tab-dialog"
		centered
		destroyOnClose
		@cancel="cancel"
		:footer="null"
		:maskClosable="false">
		<template #title>
			<div class="a-modal-tab-title" style="height: 56px">
				<a-card
					v-if="detailInfo"
					class="dialog-card-container"
					:tab-list="detailTabs.map((item:any) => ({key: item, tab: item}))"
					:active-tab-key="activeKey"
					@tabChange="(key:any) => (activeKey = key)" />
			</div>
		</template>
		<div class="flex-container-nomal" style="height: 85vh">
			<template v-if="detailInfo">
				<div class="flex1 auto-y">
					<a-row style="min-height: 100%">
						<a-col
							:span="isApproval && ['退租信息', '合约信息', '入住人信息', '账单信息'].includes(activeKey) ? 17 : 24"
							:class="{'contract-information-left': isApproval}">
							<lease-cancellation-information :data-source="detailInfo" v-if="activeKey == '退租信息'" />

							<contract-particulars
								:data-source="detailInfo"
								v-if="activeKey == '合约信息'"
								@success="getDetail"
								:approvalStatus="approvalStatus"
								@close="cancel" />

							<occupant-information
								:approvalStatus="approvalStatus"
								v-if="activeKey == '入住人信息'"
								:data-source="detailInfo.renterInfo || {}"
								:contract-type="contractType"
								:enter-renter-info="detailInfo.enterRenterInfo || {}"
								:enterpriseSignType="props.enterpriseSignType || enterpriseSignType"
								:detail-info="detailInfo || {}"
								:contract-id="contractId"
								:is-edit="![31, 32, 33, 41, 42].includes(detailInfo.contractStatus)"
								:isShow="props.isShow"
								:contractStatus="detailInfo.contractStatus"
								@success="getDetail(false)" />

							<bill-tabs
								:approvalStatus="approvalStatus"
								:type="detailInfo.type"
								:query="{
									bizId: contractId,
									houseId: detailInfo.houseId,
									order: 'asc',
									contractStatus: detailInfo.contractStatus
								}"
								:isValid="null"
								v-if="activeKey == '账单信息'"
								:contractType="contractType" />

							<!--<bill-information :data-source="detailInfo.billInfos || []" :is-handle="[-1, 3].includes(detailInfo.approvalStatus)" v-if="activeKey == '账单信息'" @bill="getDetail(false)" />-->
							<delivery-note-information
								:is-enter-prise-contract="Boolean(detailInfo.enterPriseContractId)"
								:contract-id="contractId"
								:sign-type="detailInfo.signType"
								:house-id="detailInfo.houseId"
								v-if="activeKey == '物业交割单'" />
							<!-- <approval-information v-if="activeKey == '审批信息'" /> -->
							<out-delivery-note-information v-if="activeKey == '退房交割单'" :contract-id="contractId" />
							<license-information :data-source="detailInfo" v-if="activeKey == '授权信息'" @success="getDetail(false)" />
							<!-- 1630397421914611713 contractId -->
							<energy-cost
								:contract-id="contractId"
								:contract-status="detailInfo.contractStatus"
								v-if="activeKey == '能耗费充值'" />
							<invoiceing
								:enter-type="1"
								:data-source="detailInfo"
								:id="detailInfo.id || []"
								:data-dept="{deptId: detailInfo.house.deptId, deptName: detailInfo.house.deptName}"
								v-if="activeKey == '开具发票'"
								@success="getDetail(false)" />
						</a-col>
						<a-col
							v-if="isApproval && ['退租信息', '合约信息', '入住人信息', '账单信息'].includes(activeKey)"
							:span="7"
							class="approval-process-list-right">
							<div class="d-module-title">
								<b>审批信息</b>
							</div>

							<a-timeline style="margin-top: 25px">
								<a-timeline-item v-for="(progressItem, progressIndex) in approvalSpeedProgress" :key="progressItem.id">
									<template v-if="progressItem.type == '0'">
										<a-tag color="processing" style="border-radius: 12px; margin-bottom: 10px">发起申请</a-tag>
										<a-descriptions layout="vertical" bordered size="small">
											<a-descriptions-item>
												<template #label>
													<div class="flex-space-between">
														<span>发起人：{{ progressItem.initiatorName }}</span>
														<span>{{ progressItem.operationDate }}</span>
													</div>
												</template>
												<a-row style="line-height: 30px">
													<a-col :span="24">
														<a-space :size="10">
															<span class="default-color">
																抄送人(已抄送{{ progressItem.sendPersonList.length }}人)
															</span>
															<span
																v-if="progressItem.sendPersonList.length - progressItem.readCount > 0"
																class="warning-color">
																{{ progressItem.sendPersonList.length - progressItem.readCount }}人未读
															</span>
														</a-space>
													</a-col>
													<a-col :span="24">
														<a-tag
															v-for="(item, index) in progressItem.sendPersonList"
															color="#EFF1F4"
															style="color: #4e5969"
															:key="item.name">
															<svg-icon
																:icon-class="`icon-contract-approval${item.readStatus ? '1' : '0'}`" />
															{{ item.name }}
														</a-tag>
													</a-col>
												</a-row>
											</a-descriptions-item>
										</a-descriptions>
									</template>
									<template v-else>
										<template v-if="progressItem.nodeStatus != 4">
											<template v-for="(item, index) in progressItem.approvalPersonList" :key="item.name">
												<a-tag
													:color="approvalStatusList[item.approvalStatus].color"
													style="border-radius: 12px; margin-bottom: 10px">
													{{ approvalStatusList[item.approvalStatus].name }}
												</a-tag>
												<a-descriptions layout="vertical" bordered size="small" style="margin-bottom: 10px">
													<a-descriptions-item>
														<template #label>
															<div class="flex-space-between">
																<span>审批人：{{ item.name }}</span>
																<span>{{ item.approvalTime }}</span>
															</div>
														</template>
														<a-row style="line-height: 30px">
															<a-col :span="24">
																<a-space :size="10">
																	<span class="default-color">审批类型：</span>
																	<span>{{ progressItem.approvalType == 1 ? '或签' : '会签' }}</span>
																</a-space>
															</a-col>
															<a-col :span="24" v-if="[2, 3].includes(item.approvalStatus)">
																<a-space :size="10">
																	<span class="default-color">备注：{{ item.approvalComment }}</span>
																</a-space>
															</a-col>
														</a-row>
													</a-descriptions-item>
												</a-descriptions>
											</template>
											<a-descriptions layout="vertical" bordered size="small" style="margin-bottom: 10px">
												<a-descriptions-item>
													<template #label>
														<div class="flex-space-between">
															<span>抄送人</span>
														</div>
													</template>
													<a-row style="line-height: 30px">
														<a-col :span="24">
															<a-space :size="10">
																<span class="default-color">
																	抄送人(已抄送{{ progressItem.sendPersonList.length }}人)
																</span>
																<span
																	v-if="progressItem.sendPersonList.length - progressItem.readCount > 0"
																	class="warning-color">
																	{{ progressItem.sendPersonList.length - progressItem.readCount }}人未读
																</span>
															</a-space>
														</a-col>
														<a-col :span="24">
															<a-tag
																v-for="(item, index) in progressItem.sendPersonList"
																color="#EFF1F4"
																style="color: #4e5969"
																:key="item.name">
																<svg-icon
																	:icon-class="`icon-contract-approval${item.readStatus ? '1' : '0'}`" />
																{{ item.name }}
															</a-tag>
														</a-col>
													</a-row>
												</a-descriptions-item>
											</a-descriptions>
										</template>
										<template v-else>
											<a-tag color="default" style="border-radius: 12px; margin-bottom: 10px">已撤销</a-tag>
										</template>
									</template>
								</a-timeline-item>
							</a-timeline>
						</a-col>
					</a-row>
				</div>
				<!-- 审批页面调详情 -->
				<template v-if="isApproval">
					<template v-if="approvalType === 'todo'">
						<!-- 非前合同 -->
						<div
							class="a-modal-dialog-footer"
							v-if="
								!isPriorContract &&
								![31, 32, 33].includes(detailInfo.contractStatus) &&
								[2, 3, 4].includes(detailInfo.signType) &&
								activeKey == '合约信息'
							">
							<a-button type="primary" :loading="loading" :disabled="loading" @click="getDetail(false, !isPriorContract)">
								{{ signTypeList[detailInfo.signType] + '前合同' }}
							</a-button>
						</div>
						<!-- 前合同 -->
						<div class="a-modal-dialog-footer" v-else-if="isPriorContract && activeKey == '合约信息'">
							<a-button type="primary" :loading="loading" :disabled="loading" @click="getDetail(false, !isPriorContract)">
								查看合同
							</a-button>
						</div>
					</template>
				</template>
				<!-- 非审批页面调详情 -->
				<template v-else>
					<template v-if="data.backRentRemind">
						<div
							class="a-modal-dialog-footer"
							v-if="
								store.hasPermissions(['mk_contract_tenant_qztx']) &&
								operationVisible &&
								activeKey == '合约信息' &&
								morePermissions(operationList)
							">
							<a-button type="default" @click="closeRentRemind">关闭提醒</a-button>
						</div>
					</template>
					<template v-else>
						<!--审批驳回、撤销可作废、重新提交-->
						<template
							v-if="
								[2, 4].includes(detailInfo.approvalStatus) &&
								![41].includes(detailInfo.contractStatus) &&
								store.hasPermissions(['mk_contract_tenant_zf', 'mk_contract_tenant_tjzkht'])
							">
							<div class="a-modal-dialog-footer" v-if="operationVisible && activeKey == '合约信息'">
								<a-space :size="12">
									<a-button danger v-if="store.hasPermissions(['mk_contract_tenant_zf'])" @click="handler('showToVoid')">
										作废
									</a-button>
									<!-- 补签审批撤销子合同详情不予许重新提交 additional===2 -->
									<a-button
										type="primary"
										v-if="store.hasPermissions(['mk_contract_tenant_tjzkht'])"
										@click="handler('resubmit')">
										重新提交
									</a-button>
								</a-space>
							</div>
						</template>

						<template v-else-if="[-1, 0, 3].includes(detailInfo.approvalStatus)">
							<div
								class="a-modal-dialog-footer"
								v-if="
									labelStatus[detailInfo.contractStatus].operation.length &&
									operationVisible &&
									activeKey == '合约信息' &&
									morePermissions(operationList)
								">
								<a-space :size="12">
									<template v-for="(operationItem, operationIndex) in operationList" :key="operationIndex">
										<template v-if="store.hasPermissions(operationItem.action)">
											<a-button danger v-if="operationItem.type == 'danger'" @click="handler(operationItem.field)">
												{{ operationItem.name }}
											</a-button>
											<a-button v-else :type="operationItem.type" @click="handler(operationItem.field)">
												{{ operationItem.name }}
											</a-button>
										</template>
									</template>
								</a-space>
							</div>
						</template>
					</template>
				</template>
			</template>
		</div>
		<!-- 弹窗 -->
		<template v-if="visible && detailInfo">
			<!-- 签约租客合同 -->
			<!-- <renter-sign-dialog v-model:visible="operationField.showSignContract" :contract="signContract" @success="getDetail" /> -->
			<signing-dialog
				v-model:visible="operationField.showSignContract"
				:contract="signContract"
				:signing-type="'renter'"
				@success="getDetail"
				:bizId="props.contractId"
				:approvalStatus="approvalStatus" />
			<!-- 拒绝 -->
			<refuse-dialog :id="contractId" v-model:visible="operationField.showRefuse" @success="getDetail" />
			<!-- 提醒付款 -->
			<remind-pay-dialog :data="renterInfo" v-model:visible="operationField.showRemindPay" @success="getDetail" />
			<!-- 作废 -->
			<to-void-dialog :data="renterInfo" v-model:visible="operationField.showToVoid" @success="getDetail" />
			<!-- 重置 -->
			<reset-dialog v-model:visible="operationField.showReset" @success="operationField.showSignContract = true" />

			<!-- 退租 -->
			<retreat-rent-dialog
				:contract-id="contractId"
				v-model:visible="operationField.showRetreatRent"
				:is-resubmit="isResubmit"
				@success="getDetail"
				:enterpriseSignType="enterpriseSignType"
				:bizId="props.contractId"
				:rentingOutType="rentingOutType" />

			<!-- 转租 -->
			<turn-rent-dialog
				:contract-id="contractId"
				:is-resubmit="isResubmit"
				v-model:visible="operationField.showTurnRent"
				@success="getDetail" />
			<!-- 换房 -->
			<change-house-dialog
				:enterPriseContractId="(props.enterPriseContractId as string || enterPriseContractId)"
				:contract-id="contractId"
				:is-resubmit="isResubmit"
				v-model:visible="operationField.showChangeHouse"
				@success="getDetail" />
			<!-- 邀请认证 -->
			<invite-certification-dialog :contract-id="contractId" v-model:visible="operationField.showInviteCertification" />
			<!-- 邀请签字 -->
			<invitation-signature-dialog
				:data="invitationSignature"
				v-model:visible="operationField.showInvitationSignature"
				@success="getDetail" />
			<!-- <approval v-model:visible="operationField.approvalShow" :data="approvalData" @success="getDetail" /> -->
			<!-- 退租报告模板 -->
			<rent-out-report ref="report" :data="currentRow" v-model:visible="operationField.rentingOutDialog"></rent-out-report>

			<!-- 完善合同附件 -->
			<improve-contract-attachments
				v-model:visible="operationField.showContractAttachments"
				:is-resubmit="isResubmit"
				:room-id="(detailInfo.houseId as string)"
				:biz-id="contractId"
				@success="getDetail"></improve-contract-attachments>
			<!-- 企业合同批量退租 -->
			<batch-retreat-rent
				:enter-prise-contract-id="(detailInfo?.enterPriseContractId as string)"
				v-model:visible="operationField.charterShowRetreatRent"
				@success="getDetail"
				:isShow="false"
				:resubmitId="resubmitId" />
			<!-- 企业合同作废 -->
			<contracts-cancel
				v-model:visible="operationField.charterContractsCancel"
				:info="{id: detailInfo?.enterPriseContractId, name: detailInfo?.enterPriseName}"
				@success="getDetail" />

			<!-- 退租 前置 -->
			<retreat-rent-pre
				v-model:visible="operationField.showRetreatRentPre"
				:contract-id="(contractId as string)"
				:enterPriseContractId="(detailInfo.enterPriseContractId as string)"
				:enterpriseSignType="props.enterpriseSignType || enterpriseSignType"
				:isShow="props.isShow"
				@success="getDetail" />
		</template>
	</a-modal>
</template>
<script setup lang="ts">
	import {labelStatus} from '@/utils/tenant-status'
	import {
		contractResetValid,
		getFollowList,
		getOwnerDetail,
		getRenterContractDetail,
		setBackRentRemind,
		queryRoomPlan,
		getEnterPriseInfo,
		contractCount,
		getInvoicingPrice
	} from '@/api/contract'
	import {onMounted, reactive, ref, watch, createVNode} from 'vue'
	import LeaseCancellationInformation from '@/components/contract/contract-detail-dialog/lease-cancellation-information.vue'
	import ContractParticulars from '@/components/contract/contract-detail-dialog/contract-particulars.vue'
	import OccupantInformation from '@/components/contract/contract-detail-dialog/occupant-information.vue'
	import BillInformation from '@/components/contract/contract-detail-dialog/bill-information.vue'
	import DeliveryNoteInformation from '@/components/contract/contract-detail-dialog/delivery-note-information.vue'
	import LicenseInformation from '@/components/contract/contract-detail-dialog/license-information.vue'
	import EnergyCost from '@/components/contract/contract-detail-dialog/energy/energy-cost.vue'
	import RentOutReport from '@/components/contract/tenant/rent-out-report.vue'
	import RefuseDialog from '@/components/contract/tenant/refuse-dialog.vue'
	import RemindPayDialog from '@/components/contract/tenant/remind-pay-dialog.vue'
	import ToVoidDialog from '@/components/contract/tenant/to-void-dialog.vue'
	import ResetDialog from '@/components/contract/tenant/reset-dialog.vue'
	import RetreatRentDialog from '@/components/contract/tenant/retreat-rent-dialog.vue'
	import TurnRentDialog from '@/components/contract/tenant/turn-rent-dialog.vue'
	import ChangeHouseDialog from '@/components/contract/tenant/change-house-dialog.vue'
	import OutDeliveryNoteInformation from '@/components/contract/contract-detail-dialog/out-delivery-note-information.vue'
	import InviteCertificationDialog from '@/components/contract/tenant/invite-certification.vue'
	import InvitationSignatureDialog from '@/components/contract/tenant/invitation-signature.vue'
	import {message, Modal} from 'ant-design-vue'
	import dayjs from 'dayjs'
	import {useStore} from '@/store/index'
	import {ExclamationCircleOutlined, QuestionCircleOutlined} from '@ant-design/icons-vue'
	import RenterSignDialog from '@/components/contract/tenant/renter-sign-dialog.vue'
	import {RenterContract} from '@/interface/contract'
	import XEUtils from 'xe-utils'
	import emitter from 'yuxin-base/src/utils/bus'
	import BillTabs from '@/components/finance/bill-tabs.vue'
	import {microApps} from '@/micros/apps'
	import SigningDialog from '@/components/contract/signing/signing-dialog.vue'
	import invoiceing from '@/components/contract/contract-detail-dialog/invoiceing.vue'
	import ContractsCancel from '@/components/contract/enterprise-customer-management/contracts-cancel.vue'
	import ApprovalInformation from '@/components/common/approval-information.vue'
	import {getLastApproval} from '@/api/charter-contract'
	import {isChildCheckInFun} from '@/api/charter-contract'
	import RetreatRentPre from '@/components/contract/contract-detail-dialog/renting-out/pre.vue'

	const store = useStore()

	const props = withDefaults(
		defineProps<{
			visible: boolean
			contractId: string
			// 是否租客
			isTenant?: boolean
			// 是否显示按钮
			operationVisible?: boolean
			data?: any
			// 判断是否来源于主应用
			source?: string
			// 判断是否是审批
			isApproval?: boolean
			// 审批模块类型
			approvalType?: string
			// 审批模块
			processInstanceId?: string
			isShow?: boolean
			enterpriseSignType?: string | null
			// 开具发票
			activeKeyProps?: string
			// 包租合同审批状态
			enterPriseApprovalStatus?: string | number
			/** 是否企业子合同进入 */
			enterPriseContractId?: string | null
		}>(),
		{
			visible: false,
			contractId: '',
			isTenant: true,
			operationVisible: true,
			data: {},
			source: '',
			isApproval: false,
			enterpriseSignType: null,
			enterPriseApprovalStatus: '-1'
		}
	)
	//是否重新提交
	const isResubmit = ref(false)

	const resubmitId = ref('')

	const contractType = ref(null)
	const enterpriseSignType = ref(null)
	const invitationSignature = reactive<any>({
		name: '',
		phone: '',
		contractId: ''
	})
	const emit = defineEmits(['update:visible', 'close'])
	const cancel = () => {
		emit('update:visible', false)
		emit('close')
		detailInfo.value = null
		microApps.removeApp('device')
	}
	const approvalStatus = ref('-1')
	// 人才公寓 人才id
	const talentedPersonId = ref()

	const activeKey = ref('合约信息')
	const detailInfo = ref<any>(null)
	const detailTabs = ref<any>([])
	const contractMedium = ref<any>(null)
	// const approvalData = reactive({
	// 	title: 0,
	// 	taskId: detailInfo.value.taskId
	// })

	const morePermissions = (permissions: any) => {
		let permissionsList: any = []
		permissions.forEach((item: any) => {
			if (item.action[0]) {
				permissionsList.push(item.action[0])
			}
		})
		return store.hasPermissions(permissionsList)
	}

	const rentingOutType = ref('')

	const operationList = ref<any>([])
	const renterInfo = ref<any>({})
	const isPriorContract = ref(false)
	const loading = ref(false)
	// 2 预付费 3 后付费
	const billGenerateMethod = ref(null)
	const getDetail = async (flag = true, before = false) => {
		loading.value = true
		let res: any = await getRenterContractDetail(before ? detailInfo.value.contractPid : props.contractId)
		if (res) {
			isPriorContract.value = before
			loading.value = false
			if (res.code == 200) {
				console.log(res, '0099')
				enterpriseSignType.value = res.data.enterpriseSignType
				contractType.value = res.data.contractType
				approvalStatus.value = res.data.approvalStatus
				contractMedium.value = res.data?.contractMedium
				talentedPersonId.value = res.data?.talentedPersonId
				let statusInfo = {
					name: labelStatus[res.data.contractStatus].name,
					color: labelStatus[res.data.contractStatus].color
				}

				// if (res.data.rentFreeDay > 0) {
				// 	res.data.rentFreeEndTime = dayjs(res.data.rendtFreeBeginTime)
				// 		.add(res.data.rentFreeDay, 'day')
				// 		.subtract(1, 'day')
				// 		.format('YYYY-MM-DD')
				// }
				detailInfo.value = {...res.data, statusInfo, isTenant: props.isTenant}
				if (props.isApproval) {
					detailTabs.value = labelStatus[detailInfo.value.contractStatus].detailTab.filter((item: any) => {
						return !['退房交割单', '授权信息'].includes(item)
					})
					if (
						props.approvalType === 'todo' &&
						!isPriorContract.value &&
						[31, 32, 33, 34].includes(detailInfo.value.contractStatus)
					) {
						detailTabs.value = ['退租信息', ...detailTabs.value, '退房交割单']
					}
				} else {
					detailTabs.value = labelStatus[detailInfo.value.contractStatus].detailTab
				}
				// 发票入口权限检查
				// 企业子合同不展示开具发票
				if (!store.hasPermissions(['mk_finance_invoicing_apply']) || props?.enterPriseContractId) {
					detailTabs.value = detailTabs.value.filter(e => e !== '开具发票')
				}
				if (flag) {
					activeKey.value = detailTabs.value[0]
				}
				if (props.activeKeyProps) {
					activeKey.value = props.activeKeyProps
				}
				invitationSignature.name = res.data.renterInfo.name
				invitationSignature.phone = res.data.renterInfo.phone
				invitationSignature.contractId = res.data.renterInfo.contractId
				// 操作
				operationList.value = [...labelStatus[res.data.contractStatus].operation].sort((a: any, b: any) => a.sort - b.sort)
				if (contractMedium.value === 1 && detailInfo.value.contractStatus === 12) {
					// 纸质合同
					operationList.value.push({
						name: '完善合同附件',
						field: 'showContractAttachments',
						sort: 2,
						type: 'primary',
						action: ['mk_contract_tenant_yqqz']
					})
				} else if (contractMedium.value === 2 && detailInfo.value.authType  === 1 &&detailInfo.value.contractStatus === 12) {
					operationList.value.push({
						name: '邀请签字',
						field: 'showInvitationSignature',
						sort: 1,
						type: 'primary',
						action: ['mk_contract_tenant_yqqz']
					})
					// 电子合同
				}
				console.log(operationList.value, '999')
				//1.4.7 上线屏蔽部分按钮 企业合同
				if (enterpriseSignType.value || talentedPersonId.value) {
					operationList.value = operationList.value.filter((e: any) => {
						let temp = true
						switch (e.name) {
							case '重置':
								if (enterpriseSignType.value) {
									temp = false
								}
								break
							case '转租':
								temp = false
								break
							case '换房':
								if (talentedPersonId.value) {
									temp = false
								}
								break
							case '续租':
								if (enterpriseSignType.value) {
									temp = false
								}
								break
							case '提醒付款':
								if (enterpriseSignType.value) {
									temp = false
								}
								break
						}
						return temp
					})
				}

				// 作废和提醒付款数据
				renterInfo.value = {
					name: res.data.renterInfo.name,
					phone: res.data.renterInfo.phone,
					contractPid: res.data.contractPid,
					contractId: props.contractId,
					houseId: res.data.houseId
				}

				// // 查询账单模式
				// if (res.data.houseId) {
				// 	queryRoomPlan(res.data.houseId, 2).then(res => {
				// 		console.log('res.data.billGenerateMethod===', res.data, res.data.billGenerateMethod)
				// 		// 2 预付费 3 后付费 不是预付费不展示能耗费充值
				// 		// if (res.data.billGenerateMethod !== 2) {
				// 		// 如果没有预付费的能耗费信息 || 退租状态
				// 		if (!res?.data.length || [31, 32].includes(detailInfo.value.contractStatus)) {
				// 			detailTabs.value = detailTabs.value.filter((item: any) => {
				// 				return !['能耗费充值'].includes(item)
				// 			})
				// 		}
				// 	})
				// }
			}
		}
	}

	const approvalStatusList: any = {
		0: {
			name: '待审批',
			color: 'default'
		},
		1: {
			name: '审批中',
			color: 'processing'
		},
		2: {
			name: '已驳回',
			color: 'error'
		},
		3: {
			name: '已通过',
			color: 'success'
		},
		4: {
			name: '已撤销',
			color: 'default'
		}
	}

	const approvalSpeedProgress = ref<any>({})
	// 获取审批进度信息列表
	const getApprovalDetail = () => {
		getFollowList({
			processInstanceId: props.processInstanceId
		}).then((res: any) => {
			approvalSpeedProgress.value = res.data
			console.log(res, '审批进度')
		})
	}

	type statementField = {
		[key: string]: boolean
	}
	// const contractType = ref(3)
	// 操作按钮
	const operationField = reactive<statementField>({
		//签约租客合同
		showSignContract: false,
		// 查看详情
		detailVisible: false,
		// 拒绝
		showRefuse: false,
		// 提醒付款
		showRemindPay: false,
		// 作废
		showToVoid: false,
		// 重置
		showReset: false,
		// 退租
		showRetreatRent: false,
		// 转租
		showTurnRent: false,
		// 换房
		showChangeHouse: false,
		// 邀请认证
		showInviteCertification: false,
		// 邀请签字
		showInvitationSignature: false,
		//通过，驳回，撤销
		approvalShow: false,
		//打印退租合同
		rentingOutDialog: false,
		//完善合同附件
		showContractAttachments: false,
		// 企业合同退租 作废
		charterContractsCancel: false,
		charterShowRetreatRent: false,
		// 租客合同退租结算
		showRetreatRentPre: false
	})

	// 合同签约信息
	const signContract = ref<RenterContract>({})
	const handler = async (field: string) => {
		console.log(field, 'field', detailInfo.value)
		signContract.value = XEUtils.clone(detailInfo.value, true)
		// 收租日设置如果为null 就给默认值
		signContract.value.payPattern = detailInfo.value?.payPattern ? detailInfo.value?.payPattern : 1
		signContract.value.payPatternValue = detailInfo.value?.payPatternValue !== null ? detailInfo.value?.payPatternValue : 0

		signContract.value.reset = false
		signContract.value.resubmit = false

		// 企业终止 企业子合同操作检验，退租 重新提交 作废不检验
		if (
			detailInfo.value.enterPriseId &&
			field !== 'detailVisible' &&
			field !== 'showRetreatRent' &&
			field !== 'resubmit' &&
			field !== 'showToVoid'
		) {
			const res = await getEnterPriseInfo({
				enterPriseId: detailInfo.value.enterPriseId
			})
			if (res.data?.isBreak === 2) {
				return message.warning('已与该企业终止合约,无法操作')
			}
		}

		// 如果是企业退租 重新提交 作废 调接口查询企业审批状态
		if (
			detailInfo.value.enterPriseContractId &&
			(field === 'showRetreatRent' || field === 'resubmit' || field === 'showToVoid' || field === 'showChangeHouse')
		) {
			const res = await getLastApproval(detailInfo.value.enterPriseContractId as string)
			console.log('🚀 ~ file: index.vue:730 ~ getLastApproval ~ res:', res)
			if (res.data) {
				let {approvalStatus} = res.data
				if (approvalStatus === 1 || approvalStatus === 2 || approvalStatus === 4) {
					return returnF(field)
				}
			}
		}

		// 应收款账单已开发票未冲红情况检验 作废 重置 退转换
		let billArr = ['showToVoid', 'showReset', 'showRetreatRent', 'showTurnRent', 'showChangeHouse']
		if (billArr.includes(field)) {
			const res = await getInvoicingPrice({contractId: props.contractId})

			if (Number(res.data) > 0) {
				return message.warning('操作失败！存在未收款但已开具发票的账单明细，请先作废发票申请或冲红该发票，再操作')
			}
		}

		if (field == 'showSignContract') {
			// 待处理签约
			if (signContract.value.contractStatus == 11) {
				signContract.value.signType = 1
			} else if ([23, 24, 25, 26].includes(signContract.value.contractStatus as number)) {
				// 续签
				signContract.value.signType = 2
				signContract.value.contractId = props.contractId
				// 获取租客续签数据
				// getContractDetail(detailInfo.value.id, 3)
			}
			operationField[field] = true
		} else if (field == 'showReset') {
			contractResetValid(signContract.value.id as string, {isExcludeEnergy: true}).then((res: any) => {
				if (res.data) {
					// 重置合同
					signContract.value.reset = true
					operationField.showReset = true
					// getContractDetail(detailInfo.value.id, 5)
				} else {
					message.error('已产生收支无法重置')
				}
			})
		} else if (field == 'resubmit') {
			// 重新提交
			isResubmit.value = false
			resubmitId.value = detailInfo.value.enterPriseContractId
			if (detailInfo.value.contractStatus === 32 || detailInfo.value.label === 31) {
				//重新提交退租
				isResubmit.value = true
				operationField.showRetreatRent = true
				return
			}

			if (props.enterPriseContractId) {
				isResubmit.value = true
				operationField.showChangeHouse = true
				return
			}

			signContract.value.resubmit = true
			operationField['showSignContract'] = true
		} else if (field === 'printReport') {
			downloadReport(detailInfo.value)
		} else if (field === 'settlement') {
			// 结算
			rentingOutType.value = 'settlement'
			operationField.showRetreatRent = true
		} else {
			// console.log('field', field, detailInfo.value)
			if (detailInfo.value.enterPriseContractId && (field === 'showRetreatRent' || field === 'showToVoid')) {
				resubmitId.value = ''
				// 查询当前企业合同房间数量 为1 的话跳转企业合同退租页面进行退租
				contractCount({
					contractStatus: 2,
					enterContractId: detailInfo.value.enterPriseContractId,
					excludeIds: [props.contractId]
				}).then((res: any) => {
					if (res.data === 0) {
						Modal.confirm({
							width: 470,
							title: '提示',
							content: () =>
								createVNode('div', {}, [
									createVNode('div', {
										innerHTML: '当前企业仅剩1间房,若需操作退租/作废。请从企业合同发起操作'
									})
								]),
							centered: true,
							icon: createVNode(QuestionCircleOutlined),
							okText: '关联企业合同',
							cancelText: '关闭',
							async onOk() {
								if (field === 'showRetreatRent') {
									// 退租
									operationField.charterShowRetreatRent = true
								} else {
									// 作废
									operationField.charterContractsCancel = true
								}
							}
						})
					} else {
						// console.log(detailInfo.value, 'detailInfo.value')
						// 查询当前是否有人入住
						isChildCheckInFun(detailInfo.value.id as string).then((res: any) => {
							if (res.data) {
								prompt(field)
							} else {
								if (showRetreatRentPreF(field)) return
								operationField[field] = true
							}
						})
					}
				})
			} else {
				if (showRetreatRentPreF(field)) return

				operationField[field] = true
			}
		}
	}

	const returnF = (type: any) => {
		return message.warning('企业合同正在审批流（审批中、审批驳回、审批撤销）中，请先完成企业合同审批！')
	}

	// 导出退租打印报告
	const currentRow = ref({})
	const report = ref()
	const downloadReport = async (row: any) => {
		const res = await getRenterContractDetail(row.id)
		currentRow.value = res.data
		operationField.rentingOutDialog = true
	}
	/**
	 * 关闭欠租提醒
	 */
	const closeRentRemind = () => {
		Modal.confirm({
			title: '关闭欠租提醒',
			centered: true,
			icon: createVNode(ExclamationCircleOutlined),
			content: `关闭欠租提醒后，【${detailInfo.value.renterInfo.name}】相关授权开门时将不会播报欠租提醒`,
			async onOk() {
				await setBackRentRemind({
					id: props.contractId,
					onOff: 0
				})
				setTimeout(cancel, 500)
				message.success('操作成功')
			}
		})
	}

	const signTypeList: {
		[key: string | number]: any
	} = {1: '新签', 2: '续签', 3: '转租', 4: '换房'}

	watch([() => props.visible], (newVal, oldVal) => {
		if (newVal[0]) {
			getDetail()
		}
	})

	onMounted(() => {
		if (props.source === 'dialog') {
			getDetail()

			if (props.isApproval && props.processInstanceId) {
				console.log(props.processInstanceId)
				getApprovalDetail()
			}
		}
	})

	const showBtn = () => {
		let temp = true
		if (detailInfo.value.enterPriseContractId && detailInfo.value.signType === 2) {
			temp = false
		}
		return temp
	}

	// 判断当前房间是否有人入住
	const prompt = (action: string) => {
		Modal.confirm({
			width: 470,
			title: '提示',
			content: () =>
				createVNode('div', {}, [
					createVNode('div', {
						innerHTML: `当前包租合同还有入住人,继续${
							action === 'showRetreatRent' ? '退租' : '作废'
						}将同步操作员工搬离,请确定是否继续${action === 'showRetreatRent' ? '退租' : '作废'}`
					})
				]),
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			okText: '确定',
			cancelText: '取消',
			async onOk() {
				// 判断是退租还是作废
				if (action === 'showRetreatRent') {
					// 退租
					operationField.showRetreatRentPre = true
				} else {
					// 作废
					operationField.showToVoid = true
				}
			}
		})
	}

	/** 退租前置 */
	const showRetreatRentPreF = type => {
		if (type === 'showRetreatRent') {
			// 退租结算
			operationField.showRetreatRentPre = true
			return true
		}
		return false
	}
</script>
<style lang="less">
	.contract-information-left {
		min-height: 100%;
		padding-right: 15px;
		border-right: 1px solid @border-color-light;
	}

	.approval-process-list-right {
		min-height: 100%;
		padding-left: 15px;
	}
</style>
